<template>
  <AcceptHandleHeadComponent
    ref="acceptHandleHeadRef"
    :ucolumns="ucolumns"
    :needDealNum="needDealNum"
    :needMoreQuery="true"
    :type="LableTitle.hearExamineHandle"
    @myEvent="myEvent"
    @setColumns="setColumns"
    @onSearch="onSearch"
    @onReset="reQuery"
  >
    <!-- 其他查询条件 -->
    <div class="accept_main_content_operate_left_icon icon_box" slot="headOperation">
      <div
        @click="changeMain(true)"
        :style="isMain ? 'background-color: #ccc;' : ''"
        class="accept_main_content_operate_left_icon_table algin_justity_center icon_switch"
      >
        主案件
      </div>
      <div
        @click="changeMain(false)"
        class="accept_main_content_operate_left_icon_table algin_justity_center icon_switch"
        :style="!isMain ? 'background-color: #ccc;' : ''"
      >
        子流程
      </div>
    </div>
    <!-- 其他查询条件 -->
    <div slot="more">
      <!-- 主流程搜索条件 -->
      <HearExamineHandleCollect v-if="isMain" :queryParam="queryParam" />
      <!-- 子流程搜索条件 -->
      <HearExamineHandleDetails
        v-if="!isMain"
        ref="hearExamineHandleDetailsRef"
        :queryParam="queryParam"
        :typeTotal="typeTotal"
        @f_queryUndoTaskList="queryUndoTaskList"
        @f_setCondition="s_setCondition"
      />
    </div>

    <template slot="headCenter">
      <div class="accept_content_option_div" v-show="assignShow">
        <a-button class="btn_normal_color" type="primary" @click.stop="onekeyAssign()"> 一键分派 </a-button>
        <a-alert message="请确保分派到对应的承办人和协办人" banner style="width: 300px; margin-left: 30px" />
      </div>
    </template>

    <template slot="content">
      <div class="accept_content_table">
        <!-- 表格数据 -->
        <a-table
          :scroll="scroll"
          :columns="ucolumns"
          :data-source="listData"
          :pagination="upagination"
          :loading="loading"
          rowKey="id"
          @change="tableChange"
          size="middle"
          :bordered="ubordered"
          :rowClassName="rowClassName"
          :components="header"
          ref="table"
          :key="tableCountKey"
          type="checkbox"
          :row-selection="rowSelection"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
          </span>

          <div slot="ismediateSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{
                  (record.ismediate || record.ismediate_bs) == 3200
                    ? '是'
                    : (record.ismediate || record.ismediate_bs) == 3201
                    ? '否'
                    : ''
                }}</span>
              </template>
              <span :class="{ accept_content_table_font_red: record.ismediate == 3200 || record.ismediate_bs == 3200 }">
                {{
                  (record.ismediate || record.ismediate_bs) == 3200
                    ? '是'
                    : (record.ismediate || record.ismediate_bs) == 3201
                    ? '否'
                    : ''
                }}
              </span>
            </a-tooltip>
          </div>

          <div slot="sourceSlot" slot-scope="source_text" class="beyond_hiding" style="width: 100%">
            {{ source_text }}
          </div>

          <div slot="dealNameSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ dealNameLabel(record) }}</span>
              </template>
              {{ dealNameLabel(record) }}
            </a-tooltip>
          </div>

          <div slot="acceptcodeSlot" slot-scope="acceptcode, record" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ acceptcode }}</span>
              </template>
              <span class="cursor_pointer" @click.stop="showHand(record, '4')">
                {{ acceptcode }}
              </span>
            </a-tooltip>
          </div>

          <!-- style="width: 100%;display: flex;align-items: center;justify-content: space-between;" -->
          <div slot="applynameSlot" slot-scope="applyname" class="beyond_hiding">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ applyname }}</span>
              </template>
              {{ applyname }}
            </a-tooltip>
          </div>

          <div slot="processSlot" slot-scope="process, record" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ process }}</span>
              </template>
              <a-badge v-if="record.tableList" dot>
                {{ process }}
              </a-badge>
              <span v-else>{{ process }}</span>
            </a-tooltip>
          </div>

          <div slot="targetnameSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ record.targetname_text }}</span>
              </template>
              {{ record.targetname_text }}
            </a-tooltip>
          </div>

          <div slot="thirdnameSlot" slot-scope="text, record" class="overBox" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ record.thirdname_bz || record.thirdname_bs }}</span>
              </template>
              {{ record.thirdname_bz || record.thirdname_bs }}
            </a-tooltip>
          </div>

          <div slot="mgrcateSlot" slot-scope="text, record" class="overBox" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ mgrcateLabel(record) }}</span>
              </template>
              {{ mgrcateLabel(record) }}
            </a-tooltip>
          </div>

          <div slot="proctypeSlot" slot-scope="text, record" class="overBox" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ proctypeLabel(record) }}</span>
              </template>
              {{ proctypeLabel(record) }}
            </a-tooltip>
          </div>

          <div slot="isdelaySlot" slot-scope="text, record" class="overBox" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ isdelayLabel(record) }}</span>
              </template>
              {{ isdelayLabel(record) }}
            </a-tooltip>
          </div>

          <span slot="istargetreplySlot" slot-scope="text, record" class="overBox" style="width: 100%">
            {{ record.istargetreply_bz == 3200 || record.istargetreply_bs == 3200 ? '是' : '否' }}
          </span>

          <span slot="isrestSlot" slot-scope="text, record" class="overBox" style="width: 100%">
            {{ record.isrest_bz == 3200 || record.isrest_bs == 3200 ? '是' : '否' }}
          </span>

          <div slot="statusSlot" slot-scope="text, record" class="overBox" style="width: 100%">
            {{ statusLabel(record) }}
            <a-popover v-show="record.state == '1'" placement="topLeft">
              <template slot="content">
                <span>{{
                  record.enddate
                    ? `${record.enddate.substring(0, 4)}年${record.enddate
                        .substring(5, 7)
                        .replace(/\b(0+)/gi, '')}月${record.enddate.substring(8, 10).replace(/\b(0+)/gi, '')}日截止`
                    : '无截止日期'
                }}</span>
              </template>

              <div
                :class="{
                  breathingLampGray: record.color == 'gray',
                  breathingLampRed: record.color == 'red',
                  breathingLampOrange: record.color == 'orange',
                  breathingLampGreen: record.color == 'green'
                }"
              ></div>
            </a-popover>
          </div>

          <!--时间颜色显示-->
          <div
            slot="queLeftDaySlot"
            slot-scope="text, record"
            style="width: 100%"
            v-if="record.queLeftDay != null && record.queLeftDay != undefined"
          >
            <a-tag color="green" v-if="record.queLeftDay > 7" style="color: green">
              {{ '剩余' + Math.abs(record.queLeftDay) + '天' }}</a-tag
            >
            <a-tag color="orange" v-else-if="record.queLeftDay >= 0 && record.queLeftDay < 7" style="color: orange">
              {{ '剩余' + Math.abs(record.queLeftDay) + '天' }}</a-tag
            >
            <a-tag color="red" v-else-if="record.queLeftDay < 0" style="color: red">
              {{ '逾期' + Math.abs(record.queLeftDay) + '天' }}</a-tag
            >
          </div>

          <div slot="subtimeSlot" slot-scope="subtime" class="beyond_hiding" style="width: 100%">
            {{ subtime | getTimeFormat('YYYY年M月D日') }}
          </div>

          <div slot="updatetimeSlot" slot-scope="updatetime" class="beyond_hiding" style="width: 100%">
            {{ updatetime | getTimeFormat('YYYY年M月D日') }}
          </div>

          <span slot="quedateSlot" slot-scope="text, record" class="overBox" style="width: 100%">
            {{ record.quedate_bz ? record.quedate_bz : record.quedate_bs }}
          </span>

          <span slot="sonstatusSlot" slot-scope="text, record">
            <a-tooltip
              placement="topLeft"
              v-for="(item, index) in record.sonstatusList"
              :key="index"
              style="margin-bottom: 5px"
            >
              <template slot="title">
                <span>{{ item.name }}</span>
              </template>
              <a-tag :color="item.color">
                {{ item.name }}
              </a-tag>
            </a-tooltip>
          </span>

          <template slot="operation" slot-scope="text, record">
            <a
              v-if="record.operation"
              @click.stop="showHand(record, '3')"
              v-text="record.name == '协办人确认' ? '确认' : '处理'"
            ></a>
            <span v-if="isMain" v-H_assign="record.category">
              <a-divider type="vertical" />
              <a @click.stop="showAssign(record)">分派</a>
            </span>
            <span
              v-if="isMain"
              v-show="
                (record.hearfirstid_bz || record.hearfirstid_bz || record.hearsecondid) &&
                record.sonstatusList.length == 0
              "
            >
              <a-divider type="vertical" />
              <a @click.stop="backAssign(record)">退回分派</a>
            </span>
            <span>
              <a-divider v-if="record.operation" type="vertical" />
              <a href="javascript:;" @click.stop="showHand(record, '4')">详情</a>
            </span>
          </template>
        </a-table>
      </div>

      <!-- 分派任务 -->
      <a-modal v-model="isEntrustModel" title="分派任务" destroyOnClose @ok="saveAssign()">
        <a-form-model v-if="isEntrustModel">
          <a-form-model-item label="主办人">
            <deptUserTree
              ref="firstTreeRef"
              type="user"
              :multiple="false"
              :departList="ADMREVIEW_DEPART"
              :checkedKeys="Array.of(currentDept.id)"
              :confirmBtnShow="false"
              @save="firstTreeSave"
            ></deptUserTree>
          </a-form-model-item>
          <a-form-model-item label="协办人">
            <deptUserTree
              ref="secondTreeRef"
              type="user"
              :multiple="false"
              :departList="ADMREVIEW_DEPART"
              :confirmBtnShow="false"
              @save="secondTreeSave"
            ></deptUserTree>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </template>
  </AcceptHandleHeadComponent>
</template>

<script>
import drag from '@/components/TableDrag/drag'
import { St_admreview } from '@/enumeration/St_admreview'
import { LableTitle } from '@/enumeration/LableTitle'
import { Tp_biztype } from '@/enumeration/Tp_biztype'
import { Tp_admpr } from '@/enumeration/Tp_admpr'
import { claimTaskBatch, cleanClaimTask } from '@/api/workflow/wf_MyStartInstance.js'
import { collectBusinessList, detailsBusinessList } from '@/api/workflow/mf_MyTaskUndo.js'
import { APP_USER, APP_DEPT } from '@/store/mutation-types.js'
import storage from 'store'
import moment from 'moment'
import { St_admreviewson } from '@/enumeration/St_admreviewson.js'
import { updatesHearExamineUsers } from '@/api/accept/apl_admreview.js'
import { listMgrcate } from '@/api/std/std_mgrcate.js'
import { HEAR_ASSIGN, HEAR_LEADER } from '@/utils/custom/custom-role.js'
import { Tp_categoryValue } from '@/enumeration/Tp_category.js'
import { Tp_applysourceList } from '@/enumeration/Tp_applysource'
import { Tp_proctypeValue } from '@/enumeration/Tp_proctype.js'
import { ADMREVIEW_DEPART } from '@/utils/custom/custom-depart.js'

const ucolumns = [
  {
    title: '序号',
    width: 50,
    key: 'index',
    align: 'center',
    fixed: 'left',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '状态',
    dataIndex: 'status_text',
    key: 'status_text',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'statusSlot' }
  },
  {
    title: '提醒',
    dataIndex: 'queLeftDay',
    key: 'queLeftDay',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'queLeftDaySlot' }
  },
  {
    title: '业务名称',
    dataIndex: 'process',
    key: 'process',
    width: 200,
    align: 'center'
    // scopedSlots: { customRender: 'processSlot' },
  },
  {
    title: '申请人名称',
    dataIndex: 'applyname',
    key: 'applyname',
    width: 180,
    align: 'center',
    scopedSlots: { customRender: 'applynameSlot' }
    // customCell: (record) => {
    //   return {
    //     style: {
    //       display: 'flex',
    //       alignItems: 'center'
    //     }
    //   }
    // }
  },
  {
    title: '被申请人名称',
    dataIndex: 'targetname_text',
    key: 'targetname_text',
    width: 220,
    align: 'center',
    scopedSlots: { customRender: 'targetnameSlot' }
  },
  {
    title: '期满日期',
    dataIndex: 'quedate',
    key: 'quedate',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'quedateSlot' }
  },
  {
    title: '案号',
    dataIndex: 'acceptcode',
    key: 'acceptcode',
    width: 260,
    align: 'center',
    scopedSlots: { customRender: 'acceptcodeSlot' }
  },
  {
    title: '环节',
    dataIndex: 'name',
    key: 'name',
    width: 120,
    align: 'center'
  },
  {
    title: '是否进行调解',
    dataIndex: 'ismediate_text',
    key: 'ismediate_text',
    width: 120,
    align: 'center',
    scopedSlots: { customRender: 'ismediateSlot' }
  },
  {
    title: '第三人名称',
    dataIndex: 'thirdname',
    key: 'thirdname',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'thirdnameSlot' }
  },
  {
    title: '管理类别',
    dataIndex: 'mgrcate_text',
    key: 'mgrcate_text',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'mgrcateSlot' }
  },
  {
    title: '程序类型',
    dataIndex: 'proctype_text',
    key: 'proctype_text',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'proctypeSlot' }
  },
  {
    title: '是否延期',
    dataIndex: 'isdelay_text',
    key: 'isdelay_text',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'isdelaySlot' }
  },
  {
    title: '被申请人是否已答复',
    key: 'istargetreply_text',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'istargetreplySlot' }
  },
  {
    title: '是否中止',
    key: 'isrest_text',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'isrestSlot' }
  },
  {
    title: '来源',
    dataIndex: 'source_text',
    key: 'source_text',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'sourceSlot' }
  },
  {
    title: '承办人',
    width: 150,
    key: 'dealName',
    dataIndex: 'dealName',
    align: 'center',
    scopedSlots: { customRender: 'dealNameSlot' }
  },
  {
    title: '申请时间',
    dataIndex: 'subtime',
    key: 'subtime',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'subtimeSlot' }
  },
  {
    title: '上次修改时间',
    dataIndex: 'updatetime',
    key: 'updatetime',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'updatetimeSlot' }
  },
  {
    title: '进行中',
    dataIndex: 'sonstatus_text',
    key: 'sonstatus_text',
    width: 200,
    // fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'sonstatusSlot' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 180,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'operation' }
  }
]

export default {
  data () {
    return {
      ADMREVIEW_DEPART: ADMREVIEW_DEPART, // 行政复议相关科室
      Tp_applysourceList: Tp_applysourceList,
      typeTotal: {}, // 分类统计
      isMain: true, // 父子流程切换
      applyid: null,
      assignData: {
        taskids: null, // 当前分派任务的taskids
        firstUserid: null, // 主办人userid
        firstUsername: null, // 主办人username
        secondUserid: null, // 协办人userid
        secondUsername: null // 协办人userid
      },
      isEntrustModel: false, // 分派任务树
      ucolumns: ucolumns,
      // columns: columns,
      cardColumns: ucolumns,
      needDealNum: undefined,
      queryParam: {
        acceptcode: '', // 案号
        reguserName: '', // 录入人
        applyname: '', // 申请人
        targetname: '', // 被申请人
        applyStartDate: null, // 开始时间
        applyEndDate: null, // 结束时间
        source: undefined, // 来源
        proctype: undefined, // 程序类型
        pageNumber: 1,
        pageSize: 20,
        order: 'desc',
        userid: '', // 用户id
        state: '1',
        bizenum: null,
        statusapply: [],
        f_subprocess: [],
        f_subhistory: true
      },
      listData: [],
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      loading: false,
      ubordered: true, // 表格边框是否显示
      St_admreview: St_admreview,
      Tp_biztype: Tp_biztype,
      Tp_admpr: Tp_admpr,
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      sourceType: [],
      LableTitle: LableTitle,
      St_admreviewson: St_admreviewson,
      mgrcateList: [], // 全部的行政管理单位
      mixins: [drag],
      header: undefined,
      tableCountKey: 0,
      rowSelection: {
        type: 'checkbox',
        // 不使用箭头函数就无法获取this

        // 单选
        onSelect: (record, selected, selectedRows, nativeEvent) => {
          // console.log(record, selected, selectedRows, nativeEvent)
          const list = this.rowSelection.selectRowList
          const selectedRowKeys = this.rowSelection.selectedRowKeys
          console.log(list, selectedRowKeys)
          if (!selected) {
            // 这里是取消勾选，删除对应的数组项
            selectedRowKeys.map((x, key) => {
              if (x === record.id) {
                selectedRowKeys.splice(key, 1)
              }
            })
            list.map((x, key) => {
              if (x.id === record.id) {
                list.splice(key, 1)
              }
            })
            console.log(this.rowSelection.selectedRowKeys)
          }
          if (selected) {
            // 这里是点击勾选，添加workerId字段到selectedRowKeys数组里
            this.rowSelection.selectedRowKeys.push(record.id)
            this.rowSelection.selectRowList.push(record)
            console.log(this.rowSelection.selectedRowKeys)
          }
        },
        // 全选
        onSelectAll: (selected, selectedRows, changeRows) => {
          console.log(selected, selectedRows, changeRows)
          if (selected) {
            changeRows.map(x => {
              this.rowSelection.selectedRowKeys.push(x.id)
              this.rowSelection.selectRowList.push(x)
            })
          }
          if (!selected) {
            const list = this.rowSelection.selectRowList
            const selectedRowKeys = this.rowSelection.selectedRowKeys
            changeRows.map((item, k) => {
              selectedRowKeys.map((x, key) => {
                if (x === item.id) {
                  selectedRowKeys.splice(key, 1)
                }
              })
              list.map((x, key) => {
                if (x.id === item.id) {
                  list.splice(key, 1)
                }
              })
            })
            this.rowSelection.selectRowList = list
            this.rowSelection.selectedRowKeys = selectedRowKeys
          }
        },
        selectedRowKeys: [],
        selectRowList: [],
        getCheckboxProps: record => {
          let isassign = true
          if (record.category != Tp_categoryValue.hear) {
            isassign = true
            return {
              props: {
                disabled: isassign
              }
            }
          }
          // 行政复议-审理-录入人员, 分派权限控制
          if (this.currentUser.roles) {
            this.currentUser.roles.forEach(id => {
              if (HEAR_ASSIGN.includes(id)) {
                isassign = false
              }
            })
          }
          return {
            props: {
              disabled: isassign
            }
          }
        }
      },
      assignType: 0, // 分派模式：0：单个分派，1：批量勾选分派
      scroll: { x: 1000, y: 390 }
    }
  },
  created () {

    let routeParam
    try {
      //console.log('this.$route.query.queryParam.created', this.$route.query.queryParam.TempqueryParam)
      routeParam = JSON.parse(JSON.stringify(this.$route.query.queryParam.TempqueryParam))
      this.queryParam = { ...this.queryParam, ...this.$route.query.queryParam.TempqueryParam }
    } catch {
      console.log('路由传参非json格式')
    }

    // 待处理人员
    this.headerChange()
    this.initDefaultParam()
    this.listMgrcate()
    // 判断是否是局领导
    let isLeader = false
    // 行政复议-审理-录入人员, 分派权限控制
    if (this.currentUser.roles) {
      this.currentUser.roles.forEach(id => {
        if (HEAR_LEADER.includes(id)) {
          isLeader = true
        }
      })
    }
    if (isLeader) {
      // 默认选择子流程
      this.isMain = false
    }
    this.queryUndoTaskList()
  },
  watch: {
    ucolumns: {
      handler (newValue, oldVal) {
        this.headerChange()
      },
      deep: true // 深度监听
    }
  },
  computed: {
    assignShow () {
      let isassignShow = false
      if (this.currentUser && this.currentUser.roles) {
        this.currentUser.roles.forEach(id => {
          if (HEAR_ASSIGN.includes(id)) {
            isassignShow = true
          }
        })
      }
      return isassignShow
    }
  },
  methods: {
    myEvent (e) {
      if (e) {
        this.scroll.y = this.scroll.y + e
      } else {
        this.scroll.y = 390
      }
    },
    // 子组件设置查询条件
    s_setCondition (field, value) {
      // console.log('s_setCondition', field, value)
      this.$set(this.queryParam, field, value)
    },
    // 父子流程切换
    changeMain (val) {
      if (val == this.isMain) {
        return
      }
      this.isMain = val
      this.reQuery()
    },
    // 一键分派
    onekeyAssign () {
      const selectedRows = this.rowSelection.selectRowList
      this.assignType = 1
      if (selectedRows && selectedRows.length > 0) {
        // this.assignData.taskid = record.taskid
        // this.applyid = record.applyid
        this.isEntrustModel = true
      } else {
        this.$message.warning('请勾选一条数据')
      }
    },
    // 确认分派
    async saveAssign () {
      const selectedRows = this.rowSelection.selectRowList
      if (!selectedRows || selectedRows.length < 0) {
        this.$message.warning('请勾选一条数据')
        return
      }
      if (!this.assignData.firstUserid) {
        this.$message.warning('请选择主办人')
        return
      }
      if (!this.assignData.secondUserid) {
        this.$message.warning('请选择协办人')
        return
      }
      // 1. 保存第一第二审查人信息
      let ids = []
      let taskids = []
      if (this.assignType === 0) {
        // 单个分派
        ids.push(this.applyid)
        taskids.push(this.assignData.taskid)
      } else {
        ids = selectedRows.map(data => data.applyid)
        taskids = selectedRows.map(data => data.taskid)
      }
      updatesHearExamineUsers(
        ids,
        this.assignData.firstUserid,
        this.assignData.firstUsername,
        this.assignData.secondUserid,
        this.assignData.secondUsername
      )

      // 2. 分派任务
      const { code } = await claimTaskBatch(taskids, this.assignData.firstUserid)
      if (code == 0) {
        this.$message.success('操作成功')
        this.queryUndoTaskList()
        this.isEntrustModel = false
      }
    },
    // 主办人保存
    async firstTreeSave (obj) {
      // console.log('主办人', obj)
      if (obj.id) {
        if (obj.id == this.assignData.secondUserid) {
          this.$message.warning('主办人不能和承办人为同一个人')
          this.$refs.firstTreeRef.clearForm()
          return
        }
        this.assignData.firstUserid = obj.id
        this.assignData.firstUsername = obj.name
      } else {
        this.assignData.firstUserid = null
        this.assignData.firstUsername = null
      }
    },
    // 协办人保存
    async secondTreeSave (obj) {
      // console.log('协办人', obj)
      if (obj.id) {
        if (obj.id == this.assignData.firstUserid) {
          this.$message.warning('主办人不能和承办人为同一个人')
          this.$refs.secondTreeRef.clearForm()
          return
        }
        this.assignData.secondUserid = obj.id
        this.assignData.secondUsername = obj.name
      } else {
        this.assignData.secondUserid = null
        this.assignData.secondUsername = null
      }
    },
    // 分派任务
    showAssign (record) {
      this.assignData.taskid = record.taskid
      this.applyid = record.applyid
      this.assignType = 0
      this.isEntrustModel = true
    },

    // 分派回退
    backAssign (record) {
      const confirmTitile = '是否退回当前的分派?'
      this.$confirm({
        title: '提示',
        content: confirmTitile,
        onOk: () => {
          this.doBackAssign(record)
        }
      })
    },
    async doBackAssign (record) {
      if (record) {
        const ids = []
        ids.push(record.applyid)
        updatesHearExamineUsers(ids, '', '', '', '')
        // 清空任务处理人
        const { code } = await cleanClaimTask(record.taskid)
        if (code == 0) {
          this.$message.success('操作成功')
          this.queryUndoTaskList()
        }
      }
    },

    /**
     * 显示处理界面
     */
    showHand (record, pattern) {
      console.log('record', record.taskid)
      // 若是执行强制执行，则显示执行界面
      if (record.processkey == 'EXECUTE_FORCE' || record.processkey == 'EXECUTE_PERFORM') {
        record.isExecute = true
        record.isExecuteEdit = false
      }
      record.TempqueryParam = this.queryParam
      this.$router.push({
        path: `/HearExamineProcessedOperation/${record.taskid}/${pattern}`,
        query: {
          url: '/HearExamineHandle',
          queryParam: record
        }
      })
    },

    headerChange () {
      console.log('移动后', this.ucolumns)
      this.header = {
        header: {
          cell: drag.methods.initDrag(this.ucolumns)
        }
      }
    },
    setColumns (columns) {
      console.log('重置前', this.ucolumns)
      // tableCountKey自增是为了让表格控件每次销毁强制更新
      this.tableCountKey += 1
      this.ucolumns = columns
      // this.ucolumns = columns
      console.log('重置后', this.ucolumns)
      this.setCardColumns()
    },
    onSearch (val) {
      this.queryParam.acceptcode = val
      this.queryParam.pageNumber = 1
      this.queryParam.pageSize = 20
      this.queryUndoTaskList()
    },
    /**
     * 初始化设置默认值
     */
    initDefaultParam () {
      this.currentUser = storage.get(APP_USER)
      this.queryParam.userid = this.currentUser.userId
      this.queryParam.statusapply.push(this.St_admreview['accept'].value)
      this.sourceType = this.Tp_applysourceList
      this.queryParam.bizenum = this.Tp_biztype['accept'].value
      this.queryParam.f_subprocess = [
        Tp_proctypeValue['HEAR_DECISION'],
        Tp_proctypeValue['HEAR_TRANSFORM'],
        Tp_proctypeValue['HEAR_DELAY'],
        Tp_proctypeValue['HEAR_HEARING'],
        Tp_proctypeValue['HEAR_MEDIATE'],
        Tp_proctypeValue['HEAR_REST'],
        Tp_proctypeValue['HEAR_RESTORE'],
        Tp_proctypeValue['HEAR_MOBILIZE'],
        Tp_proctypeValue['HEAR_STOP'],
        Tp_proctypeValue['HEAR_SURVEY'],
        Tp_proctypeValue['HEAR_IDENTIFY'],
        Tp_proctypeValue['HEAR_EXPERT'],
        Tp_proctypeValue['HEAR_INQUEST'],
        Tp_proctypeValue['HEAR_TRAWL'],
        Tp_proctypeValue['HEAR_THIRDER'],
        Tp_proctypeValue['HEAR_CHANGE_FIRTPER'],
        Tp_proctypeValue['HEAR_CHANGE_SECONDPER'],
        Tp_proctypeValue['EXECUTE_FORCE_UNIT'],
        Tp_proctypeValue['EXECUTE_SELF'],
        Tp_proctypeValue['EXECUTE_PERFORM'],
        Tp_proctypeValue['EXECUTE_FORCE_LAW']
      ]
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery () {
      this.queryParam = {
        acceptcode: '', // 案号
        reguserName: '', // 录入人
        applyname: '', // 申请人
        targetname: '', // 被申请人
        applyStartDate: null, // 开始时间
        applyEndDate: null, // 结束时间
        source: undefined, // 来源
        proctype: undefined, // 程序类型
        pageNumber: 1,
        pageSize: 20,
        order: 'desc',
        userid: '', // 用户id
        state: '1',
        bizenum: null,
        statusapply: [],
        isCorrelation: true,
        f_subprocess: [
          Tp_proctypeValue['HEAR_DECISION'],
          Tp_proctypeValue['HEAR_TRANSFORM'],
          Tp_proctypeValue['HEAR_DELAY'],
          Tp_proctypeValue['HEAR_HEARING'],
          Tp_proctypeValue['HEAR_MEDIATE'],
          Tp_proctypeValue['HEAR_REST'],
          Tp_proctypeValue['HEAR_RESTORE'],
          Tp_proctypeValue['HEAR_MOBILIZE'],
          Tp_proctypeValue['HEAR_STOP'],
          Tp_proctypeValue['HEAR_SURVEY'],
          Tp_proctypeValue['HEAR_IDENTIFY'],
          Tp_proctypeValue['HEAR_EXPERT'],
          Tp_proctypeValue['HEAR_INQUEST'],
          Tp_proctypeValue['HEAR_TRAWL'],
          Tp_proctypeValue['HEAR_THIRDER'],
          Tp_proctypeValue['HEAR_CHANGE_FIRTPER'],
          Tp_proctypeValue['HEAR_CHANGE_SECONDPER'],
          Tp_proctypeValue['EXECUTE_FORCE_UNIT'],
          Tp_proctypeValue['EXECUTE_SELF'],
          Tp_proctypeValue['EXECUTE_PERFORM'],
          Tp_proctypeValue['EXECUTE_FORCE_LAW']
        ],
        f_subhistory: true
      }
      if (this.$refs.hearExamineHandleDetailsRef) {
        this.$refs.hearExamineHandleDetailsRef.f_reset()
      }
      this.initDefaultParam()
      this.queryUndoTaskList()
    },

    tableChange (upagination, filters, sorter, { currentDataSource }) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryUndoTaskList()
    },
    tableChangeOther (upagination) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryUndoTaskList()
    },
    getCpQueryParam () {
      // 时间转换
      const cpQueryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.applyStartDate?.format) {
        cpQueryParam.applyStartDate = this.queryParam.applyStartDate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.applyEndDate?.format) {
        cpQueryParam.applyEndDate = this.queryParam.applyEndDate.format('YYYY-MM-DD') + ' 23:59:59'
      }
      return cpQueryParam
    },

    async queryUndoTaskList () {
      const queryParam = this.getCpQueryParam()
      if (queryParam.acceptcode) {
        queryParam.acceptcode = queryParam.acceptcode.toString().trim()
      }
      if (queryParam.targetname) {
        queryParam.targetname = queryParam.targetname.toString().trim()
      }
      if (queryParam.applyname) {
        queryParam.applyname = queryParam.applyname.toString().trim()
      }
      this.loading = true
      const _this = this
      let res
      // 根据主子状态调用接口
      if (this.isMain) {
        res = await collectBusinessList({ userid: queryParam.userid }, queryParam).finally(() => {
          this.loading = false
        })
        if (res.data.records && res.data.records.length > 0) {
          res.data.records.forEach(item => {
            const sonstatusList = []
            if (item.sonstatus != '' && item.sonstatus != null) {
              const sonstatusArray = item.sonstatus.split(',')
              sonstatusArray.forEach(sonStatus => {
                const sonItem = {}
                sonItem.key = sonStatus
                sonItem.name = _this.St_admreviewson[Number(sonStatus)].name
                sonItem.color = _this.St_admreviewson[Number(sonStatus)].color
                sonstatusList.push(sonItem)
              })
            }
            item.sonstatusList = sonstatusList
          })
        }
      } else {
        res = await detailsBusinessList({ userid: queryParam.userid }, queryParam).finally(() => {
          this.loading = false
        })
        // 给相同案号的数据加序号后缀
        if (res.data?.records && res.data?.records.length > 0) {
          let index = 1
          let acceptCode = res.data.records[0].acceptcode
          let transIndex = 0

          res.data.records.forEach((item, order) => {
            if (item.acceptcode != acceptCode) {
              index = 1
              acceptCode = item.acceptcode
            }
            item.acceptcodeTemp = item.acceptcode
            item.acceptcode = item.acceptcode + '-' + index++

            // 待处理的放前面
            if (item['operation']) {
              const temp = res.data.records[transIndex]
              res.data.records[transIndex] = item
              res.data.records[order] = temp
              // console.log('transIndex', transIndex)
              transIndex++
            }
          })
          // 1 进行统计分类
          const acceptArr = []
          this.typeTotal = { investiga: 0 }
          for (let i = res.data.records.length - 1; i >= 0; i--) {
            // 根据子流程状态进行过滤
            if (this.queryParam.isTodo == 3200 && res.data.records[i]['operation']) {
              res.data.records.splice(i, 1)
              continue
            } else if (this.queryParam.isTodo == 3201 && !res.data.records[i]['operation']) {
              res.data.records.splice(i, 1)
              continue
            }

            const type = String(res.data.records[i]['type_bs'])
            if (res.data.records[i]['operation']) {
              // console.log('type', type)
              if (type in this.typeTotal) {
                this.$set(this.typeTotal, type, this.typeTotal[type] + 1)
              } else {
                this.$set(this.typeTotal, type, 1)
              }
              if (
                [
                  Tp_proctypeValue['HEAR_MOBILIZE'],
                  Tp_proctypeValue['HEAR_SURVEY'],
                  Tp_proctypeValue['HEAR_IDENTIFY'],
                  Tp_proctypeValue['HEAR_EXPERT'],
                  Tp_proctypeValue['HEAR_INQUEST']
                ].includes(Number(type))
              ) {
                // 调查父类汇总
                this.$set(this.typeTotal, 'investiga', this.typeTotal['investiga'] + 1)
              }
            }
            // 2 根据查询条件过滤
            if (this.queryParam.type) {
              if (type != this.queryParam.type) {
                if (!acceptArr.includes(res.data.records[i]['acceptcodeTemp'])) {
                  acceptArr.push(res.data.records[i]['acceptcodeTemp'])
                }
                res.data.records.splice(i, 1)
              }
            }
          }
          // console.log('acceptArr', acceptArr)
          // 3 把查询条件过滤后, 类型已知但是不能编辑的记录删除
          if (this.queryParam.type) {
            for (let i = res.data.records.length - 1; i >= 0; i--) {
              if (
                this.queryParam.type == res.data.records[i]['type_bs'] &&
                acceptArr.includes(res.data.records[i]['acceptcodeTemp']) &&
                !res.data.records[i]['operation']
              ) {
                res.data.records.splice(i, 1)
              }
            }
            // 根据长度重新赋值页码
            if (res.data.total != res.data.records.length) {
              res.data.total = res.data.records.length
              const pageStart = (res.data.current - 1) * res.data.size
              let pageEnd = pageStart + res.data.size
              if (res.data.total < pageEnd) {
                pageEnd = res.data.total
              }
              res.data.records = res.data.records.splice(pageStart, pageEnd)
            }
          }
          // res.data.records = res.data.records.slice(pageStart, pageEnd)
        }
      }
      // console.log('this.queryParam.type', this.queryParam.type)
      this.listData = res.data?.records || []
      this.upagination.total = res.data.total
      this.upagination.current = res.data.current
      this.upagination.pageSize = res.data.size
      this.needDealNum = res.data.total
      // 对应枚举值设置
      this.setEnumData(this.listData)
      this.listData.forEach(el => {
        if (el.children && el.children.length > 0) {
          this.setEnumData(el.children)
        }
      })
    },
    // 设置对应的枚举值
    setEnumData (listData) {
      if (listData && listData.length > 0) {
        for (var index = 0; index < listData.length; index++) {
          const item = listData[index]
          if (item) {
            // 被申请人名称
            item.targetname_text = this.targetNameLable(item)
            // 是否进行调解
            item.ismediate_text =
              (item.ismediate || item.ismediate_bs) == 3200
                ? '是'
                : (item.ismediate || item.ismediate_bs) == 3201
                ? '否'
                : ''
            // 来源
            item.source_text = this.sourceLable(item.source)
            // 是否行政不作为
            if (item.isomission_bz == 3200 || item.isomission_bs == 3200) {
              // 行政不作为
              item.prtype_text = '行政不作为'
            } else {
              const prtype = item.prtype_bz || item.prtype_bs
              item.prtype_text = this.Tp_admpr[prtype] ? this.Tp_admpr[prtype].name : ''
            }
            // 超时时间
            // 状态
            item.status_text = this.statusLabel(item)
            // 判断当前的是否超时
            if (item.state == '1' && item.leftDay && item.leftDay <= 3) {
              item.status_text = '剩余' + item.leftDay + '天逾期'
              item.isTimeout = true
            } else {
              item.isTimeout = false
            }
            // 管理类型
            item.mgrcate_text = this.mgrcateLabel(item)
            // 程序类型
            item.proctype_text = this.proctypeLabel(item)
            // 是否延期
            item.isdelay_text = this.isdelayLabel(item)
            // 被申请人是否已答复
            item.istargetreply_text = item.istargetreply_bz == 3200 || item.istargetreply_bs == 3200 ? '是' : '否'
            // 是否中止
            item.isrest_text = item.isrest_bz == 3200 || item.isrest_bs == 3200 ? '是' : '否'

            // 进行中状态
            const sonstatusLabels = []
            if (item.sonstatusList && item.sonstatusList.length > 0) {
              for (const sonstatus of item.sonstatusList) {
                sonstatusLabels.push(sonstatus.name)
              }
              item.sonstatus_text = sonstatusLabels.join('，')
            }
            let quedate = item.quedate_bz ? item.quedate_bz : item.quedate_bs
            if (quedate && item.type_bs != Tp_proctypeValue.HEAR_REST) {
              // YYYY年mm月DD日
              var year = quedate.substring(0, quedate.indexOf('年'))
              var month = quedate.substring(quedate.indexOf('年') + 1, quedate.indexOf('月'))
              var day = quedate.substring(quedate.indexOf('月') + 1, quedate.indexOf('日'))
              quedate = year + '-' + month + '-' + day
              // moment
              item.queLeftDay = moment(quedate).diff(moment(new Date()), 'days')
            } else {
              item.queLeftDay = null
            }
          }
        }
      }
    },

    // 状态转换显示
    statusLabel (record) {
      const val = record.status_bz || record.status_bs
      if (val == this.St_admreview['accept'].value) {
        return '审理中'
      }
      for (const key in this.St_admreview) {
        if (this.St_admreview[key].value == val) {
          return this.St_admreview[key].name
        }
      }
      return val
    },
    // 来源转换显示
    sourceLable (val) {
      for (const key in this.Tp_applysourceList) {
        if (this.Tp_applysourceList[key].value == val) {
          return this.Tp_applysourceList[key].name
        }
      }
      return val
    },
    // 被申请人查询显示
    targetNameLable (record) {
      const val = record.targetname_bz || record.targetname_bs
      return val
    },

    /**
     * 查询全部的行政管理单位
     */
    async listMgrcate () {
      await listMgrcate().then(res => {
        if (res.code == 0) {
          this.mgrcateList = res.data
        }
      })
    },
    /**
     * 管理类别展示
     * @param {*} record
     */
    mgrcateLabel (record) {
      const mgrcate = record.mgrcate_bz || record.mgrcate_bs
      let mgrcateLabel = ''
      if (this.mgrcateList && mgrcate) {
        const mgrcates = mgrcate.split(',')
        const mgrcateLabelArr = []
        for (const mgrcateKey of mgrcates) {
          for (const mgrcateItem of this.mgrcateList) {
            if (mgrcateItem.id == mgrcateKey) {
              mgrcateLabelArr.push(mgrcateItem.name)
            }
          }
        }
        if (mgrcateLabelArr && mgrcateLabelArr.length > 0) {
          mgrcateLabel = mgrcateLabelArr.join('，')
        }
        return mgrcateLabel
      }
      return ''
    },
    /**
     * 程序类型显示
     */
    proctypeLabel (record) {
      const proctype = record.proctype_bz || record.proctype_bs
      const enumItem = this.$store.getters.getEnumItem('Tp_apptype').filter(item => item.value == proctype)[0]
      return enumItem ? enumItem.label : ''
    },
    /**
     * 是否延期展示
     */
    isdelayLabel (record) {
      const isdelay = record.isdelay_bz || record.isdelay_bs
      const enumItem = this.$store.getters.getEnumItem('Tp_yesno').filter(item => item.value == isdelay)[0]
      return enumItem ? enumItem.label : ''
    },

    rowClassName (record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    },

    /**
     * 案件承办人
     * @param {} record
     */
    dealNameLabel (record) {
      let dealName = record.hearfirstname_bz || record.hearfirstname_bs
      if (dealName && (record.hearsecondname_bz || record.hearsecondname_bs)) {
        dealName = dealName + '，' + (record.hearsecondname_bz || record.hearsecondname_bs)
      }
      return dealName
    },

    setCardColumns () {
      const columns = this.ucolumns.filter(child => child.key != 'index' && child.key != 'action')
      this.cardColumns = JSON.parse(JSON.stringify(columns))
    }
  },
  components: {
    AcceptHandleHeadComponent: () => import('@/views/accept/component/AcceptHandleHeadComponent.vue'),
    deptUserTree: () => import('@/views/base/DeptUserTree.vue'),
    HearExamineHandleCollect: () => import('@/views/hear/component/HearExamineHandleCollect.vue'),
    HearExamineHandleDetails: () => import('@/views/hear/component/HearExamineHandleDetails.vue')
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/apply/breathingLamp.scss';
.icon_box {
  // border: 1px solid red;
  width: 150px;
  min-width: 150px;
  margin-right: 8px;
}
// ::v-deep .ant-table-tbody > tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected) > td {
//   background: #eff3f6 !important;
//   // color: red;
// }
// ::v-deep .ant-table-fixed {
//   .ant-table-row-hover,
//   .ant-table-row-hover > td {
//     background-color: #eff3f6 !important;
//   }
// }

.icon_switch {
  cursor: pointer;
  font-weight: 550;
  width: 50%;
}
.cursor_pointer:hover {
  color: #55a7f5;
}
.accept_content {
  &_option {
    &_div {
      display: flex;
      margin-left: 30px;
      align-items: center;
    }
    &_a {
      width: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #1890ff;
      font-size: 16px;
      background-color: transparent;
      outline: none;
      cursor: pointer;
      margin-left: 20px;
      font-weight: bold;
    }
  }
  &_table {
    &_font_red {
      color: #ca0000;
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 400;
    }

    ::v-deep .ant-table-row-cell-break-word {
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 400;
      color: #2c2c2c;
    }

    ::v-deep .ant-table-thead > tr > th {
      height: 50px;
    }

    ::v-deep .ant-table-row-cell-break-word {
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 600;
      color: #2c2c2c;
    }

    // ::v-deep .ant-pagination-total-text {
    //   font-size: 16px;
    //   font-family: 'PingFang-SC-Heavy';
    //   font-weight: 400;
    //   color: #8e97b9;
    // }

    ::v-deep .ant-table-body,
    .ant-table-header {
      word-break: break-all;
      &::-webkit-scrollbar {
        width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
        // height: 10px;
      }
      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #a2c6e1;
      }
      &::-webkit-scrollbar-track {
        // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        border-radius: 5px;
        background: transparent;
      }
    }
  }
}
</style>
